#!/bin/bash
source /home/shell/util.sh

# 预置插件
jenkins_plugins=('sshd' 'ssh-slaves' 'localization-support' 'trilead-api' 'localization-zh-cn' 'apache-httpcomponents-client-4-api' 'credentials' 'popper2-api'
  'command-launcher' 'caffeine-api' 'display-url-api' 'git-client' 'git' 'jdk-tool' 'jsch' 'mailer' 'script-security' 'structs' 'credentials-binding'
  'ssh-credentials' 'scm-api' 'workflow-scm-step' 'workflow-step-api' 'workflow-api' 'workflow-support' 'workflow-job' 'javadoc' 'jaxb' 'jquery' 'git-parameter'
  'bootstrap4-api' 'jackson2-api' 'checks-api' 'echarts-api' 'plugin-util-api' 'junit' 'maven-plugin' 'pipeline-maven' 'h2-api' 'bootstrap5-api'
  'cloudbees-folder' 'config-file-provider' 'branch-api' 'snakeyaml-api' 'font-awesome-api' 'jquery3-api' 'popper-api' 'plain-credentials' 'token-macro'
  'bouncycastle-api' 'date-parameter' 'nodejs' 'matrix-auth' 'extended-read-permission' 'role-strategy' 'publish-over' 'publish-over-ssh' 'dingding-notifications');

# 安装函数
function install_jenkins () {
    requireJava
    ln -s /opt/jdk/bin/java /usr/bin/java
    if [ "$(ostype)" == "Ubuntu" ]; then
        printInfo "Jenkins(ubuntu) 版本："
        curl -sL https://repo.huaweicloud.com/jenkins/debian/|grep $(date +%Y)|grep -Po "jenkins_.*_all.deb"|uniq|perl -pe "s/jenkins_(\d+.\d+)_all.deb/\1/g"
        while [ true ]; do
            read -p "请选择版本：" version
            if [[ -z "${version}" ]]; then
                printFail "请重新输入版本！"
                continue;
            else
                break;
            fi
        done
        apt install -y daemon fontconfig
        fc-cache --force

        dpkg-install-fromurl https://repo.huaweicloud.com/jenkins/debian/jenkins_${version}_all.deb
    else
        yum install -y fontconfig daemonize
        fc-cache --force
        printInfo "Jenkins(Redhat) 版本："
        curl -sL https://repo.huaweicloud.com/jenkins/redhat/|grep $(date +%Y)|grep -Po "jenkins-.*.noarch.rpm"|uniq|perl -pe "s/jenkins-(\d+.\d+)-1.1.noarch.rpm/\1/g"|head -10
        while [ true ]; do
            read -p "请选择版本：" version
            if [[ -z "${version}" ]]; then
                printFail "请重新输入版本！"
                continue;
            else
                break;
            fi
        done
        # sudo rpmkeys --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
        sudo rpmkeys --import /home/shell/support/jenkins/jenkins.io.key
        gpgpubkey=`rpm -qi gpg-pubkey-45f2c3d5-5e81efb9`
        if [ '$gpgpubkey' == '未安装软件包 gpg-pubkey-45f2c3d5-5e81efb9' ];
        then
            echo -e "\033[91m\033[1m\033[5m密钥下载失败，程序退出！\033[0m"
            exit;
        else
            echo -e "\033[92m密钥导入成功\033[0m"
        fi
        # 安装Jenkins
        download /opt/jenkins.noarch.rpm https://repo.huaweicloud.com/jenkins/redhat/jenkins-${version}.noarch.rpm
        rpm -ivh /opt/jenkins.noarch.rpm
        rm -rf /opt/jenkins.noarch.rpm
    fi
    
}